package cn.yshujia.filter;

import cn.yshujia.constant.SystemConst;
import cn.yshujia.domain.LoginUser;
import cn.yshujia.utils.SecurityUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author YShuJia
 * @create 2024/4/23
 * @description jwt过滤器
 */

@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
	
	protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain chain) throws IOException, ServletException {
		String jwt = request.getHeader(SystemConst.TOKEN_KEY);
		LoginUser loginUser = SecurityUtils.getLoginUser();
		// 获取用户信息
		if (!ObjectUtils.isEmpty(jwt) && ObjectUtils.isEmpty(SecurityUtils.getAuthentication())) {
			// 获取用户信息 TODO 传入 jwt
			loginUser = SecurityUtils.getLoginUser();
		}
		/*if (null != loginUser) {
			// 判断token有效时长 更新 token 和用户信息
			if (JwtTokenUtils.isRefresh(SecurityUtils.getToken(loginUser.getUser().getId()))) {
				String token = JwtTokenUtils.genAccessToken(loginUser.getUser().getId());
				loginUser.getUser().setToken(token);
				SecurityUtils.setUserVO(loginUser.getUser());
				SecurityUtils.setToken(loginUser.getUser().getId(), token);
			}
			// 存储 用户信息到上下文
			UsernamePasswordAuthenticationToken securityContextToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
			securityContextToken.setDetails((new WebAuthenticationDetailsSource()).buildDetails(request));
			SecurityUtils.setAuthentication(securityContextToken);
		}*/
		chain.doFilter(request, response);
	}
}